'''
admin.py - Administration interface for The Living History
Copyright 2009 Mithun Chaubey
'''

import lh_user

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import os


class MainPage(webapp.RequestHandler):
    ''' Handler for main admin page '''
    def get(self):
        '''Displays welcome page using admin_index.html'''

        current_user = lh_user.get_current_user(self)
        if not current_user.has_perm('admin_access'):
            self.response.out.write("Access Denied")

        else:
            template_values = {
                'current_user': current_user,
                'activetab': 'main'
            }

            path = os.path.join(os.path.dirname(__file__), 'templates/admin_index.html')
            self.response.out.write(template.render(path, template_values))

class admin_users(webapp.RequestHandler):
    '''Handler for user administration'''
    def get(self):
        '''Displays the user administration page using users.html'''

        current_user = lh_user.get_current_user(self)
        if not current_user.has_perm('admin_access'):
            self.response.out.write("Access Denied")

        else:

            lh_users = lh_user.lh_user.all()

            template_values = {
                'lh_users' : lh_users,
                'groups': lh_user.group.all(),
                'current_user': current_user,
                'activetab': 'users'
            }

            path = os.path.join(os.path.dirname(__file__), 'templates/users.html')
            self.response.out.write(template.render(path, template_values))

class addUser(webapp.RequestHandler):
    '''Handler for 'add user' requests'''
    def post(self):
        '''Adds a user to the database'''

        # Authenticate
        current_user = lh_user.get_current_user(self)
        if not current_user.has_perm('user_edit'):
            self.response.out.write("Access Denied")
        else:

            # Check username
            if(lh_user.user_by_username(self.request.get('username')) != None):
                self.response.out.write('Error: User by that name exists -- ' + user.username)
            else:
                # Check google username
                if(lh_user.user_by_google_name(self.request.get('google_username')) != None):
                    self.response.out.write('Error: User is already registered with that google account')
                else:
                    user = lh_user.lh_user()

                    # Validate
                    #

                    user.username = self.request.get('username')
                    user.google_user = lh_user.google_user_by_name(self.request.get('google_username'))

                    # Assign permissions
                    #

                    # Put in datastore so there is a key (for group association)
                    user.put()

                    # Associate with groups
                    groups = self.request.get('groups', allow_multiple=True)
                    for grpname in groups:
                        grp = lh_user.group_by_name(grpname)
                        if(grp != None):
                            user.add_group(grp)

                    self.redirect('/admin/users')

class editUser(webapp.RequestHandler):
    '''Handler for editing user details'''
    def get(self, username):
        '''Displays form for editing user details using editUser.html'''

        current_user = lh_user.get_current_user(self)
        if not current_user.has_perm('user_edit'):
            self.response.out.write("Access Denied")
        else:
            
            user = lh_user.user_by_username(username)
            if(user == None):
                self.response.out("User by that name doesn't exist")
            else:

                template_values = {
                    'user': user,
                    'user.groups': user.groups(),
                    'groups': lh_user.group.all(),
                    'current_user': current_user,
                    'activetab': 'users'
                }

                path = os.path.join(os.path.dirname(__file__), 'templates/editUser.html')
                self.response.out.write(template.render(path, template_values))

    def post(self, username):
        '''Edits user details in datastore based on form input'''

        current_user = lh_user.get_current_user(self)
        if not current_user.has_perm('user_edit'):
            self.response.out.write("Access Denied")
        else:

            user = lh_user.user_by_username(username)
            if(user == None):
                self.response.out("User by that name doesn't exist")
            else:

                user.username = self.request.get('username')
                user.google_user = lh_user.google_user_by_name(self.request.get('google_username'))

                # Associate with groups
                groups = self.request.get('groups', allow_multiple=True)
                for grpname in groups:
                    grp = lh_usre.group_by_name(grpname)
                    if(grp != None):
                        user.add_group(grp)

                # Permissions
                #

                user.put()
                
                self.redirect('/admin/users')
            

class admin_groups(webapp.RequestHandler):
    '''Handler for user group administration'''
    def get(self):
        '''Displays group administration page using groups.html'''

        current_user = lh_user.get_current_user(self)
        if not current_user.has_perm('admin_access'):
            self.response.out.write("Access Denied")
        else:
            groups = lh_user.group.all()

            template_values = {
                'groups' : groups,
                'current_user': current_user,
                'activetab': 'groups'
            }

            path = os.path.join(os.path.dirname(__file__), 'templates/groups.html')
            self.response.out.write(template.render(path, template_values))

class addGroup(webapp.RequestHandler):
    '''Handler for adding a user group'''
    def post(self):
        '''Adds a group to the datastore'''

        # Authenticate
        current_user = lh_user.get_current_user(self)
        if not current_user.has_perm('group_edit'):
            self.response.out.write("Access Denied")
        else:

            grp = lh_user.group()
            grp.name = self.request.get('name')
            grp.permissions = self.request.get('permissions', allow_multiple=True)
            grp.put()

            self.redirect('/admin/groups')

class editGroup(webapp.RequestHandler):
    '''Handler for editing user group details'''
    def get(self, name):
        '''Displays form for editing group details using editGroup.html'''

        # Authenticate
        current_user = lh_user.get_current_user(self)
        if not current_user.has_perm('group_edit'):
            self.response.out.write("Access Denied")
        else:

            # Get by name
            grp = lh_user.group_by_name(name)
            if(grp == None):
                self.response.out.write("Group by that name not found")
            else:

                template_values = {
                    'group' : grp,
                    'current_user': current_user,
                    'activetab': 'groups'
                }
                
                path = os.path.join(os.path.dirname(__file__), 'templates/editGroup.html')
                self.response.out.write(template.render(path, template_values))
        
    def post(self, name):
        '''Edits group details in datastore using form input'''

        # Authenticate
        current_user = lh_user.get_current_user(self)
        if not current_user.has_perm('group_edit'):
            self.response.out.write("Access Denied")
        else:

            # Get by name
            grp = lh_user.group_by_name(name)
            if(grp == None):
                self.response.out.write("Group by that name not found")
            else:
                    
                # Set values
                grp.name = self.request.get('name')
                grp.permissions = self.request.get('permissions', allow_multiple=True)

                # Put()
                grp.put()

                self.redirect('/admin/groups')
